package com.qf.taobei.controller;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.qf.taobei.entity.Discount;
import com.qf.taobei.entity.RespBean;
import com.qf.taobei.entity.User;
import com.qf.taobei.entity.vo.OrderDetailsVo;
import com.qf.taobei.entity.vo.ViewDiscount;
import com.qf.taobei.entity.vo.ViewOrderDetails;
import com.qf.taobei.service.DiscountService;
import com.qf.taobei.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Api(tags = "优惠券模块")
@RestController
@RequestMapping("/disc")
public class DiscountController {

    @Autowired
    private DiscountService discountService;

    @Autowired
    private OrderService orderService;

    //根据优惠券id查询优惠券信息
    @ApiOperation("根据优惠券id查询优惠券信息")
    @GetMapping("/getDiscount")
    public RespBean getDiscount(Integer id){
        Discount discount = discountService.queryDiscountById(id);
        return RespBean.respSuccess("查询成功",discount);
    }

    //修改优惠券信息
    @ApiOperation("修改优惠券信息")
    @PostMapping("/updateDis")
    public RespBean updateDiscount(Discount discount){
        Integer res = discountService.updateDiscount(discount);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        return RespBean.respSuccess("修改成功");
    }

    /**
     * 用户领取优惠券
     * @param id
     * @return
     */
    @ApiOperation("用户领取优惠券")
    @PostMapping("/getDis")
    public RespBean getDis(HttpSession session,Integer id){
        User user = (User) session.getAttribute("user");
        Integer uid = user.getId();
        Integer res = discountService.getDis(uid,id);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        return RespBean.respSuccess("领取成功");
    }

    /**
     * 删除优惠券
     * @param id    优惠券id
     * @return
     */
    @ApiOperation("删除优惠券")
    @PostMapping("/delDiscount")
    public RespBean delDiscount(Integer id){
        discountService.delDiscount(id);
        return RespBean.respSuccess("删除成功");
    }

    /**
     * 添加优惠券信息
     * @param discount
     * @return
     */
    @ApiOperation("添加优惠券")
    @PostMapping("/addDiscount")
    public RespBean addDiscount(HttpServletRequest request,Discount discount){
        Integer res = discountService.addDiscount(request,discount);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        return RespBean.respSuccess("添加成功");
    }

    //查询所有优惠券
    @ApiOperation("查询所有优惠券")
    @GetMapping("/getAllDis")
    public RespBean getAllDis(){
        List<ViewDiscount> discountList = discountService.queryAllDiscount();
        return RespBean.respSuccess("查询成功",discountList);
    }

    //查询用户有哪些优惠券
    @ApiOperation("查询用户有哪些优惠券")
    @GetMapping("/getDisByUid")
    public RespBean getDisByUid(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<ViewDiscount> discountList = discountService.queryDiscountByUid(user.getId());
        return RespBean.respSuccess("查询成功",discountList);
    }


    //查看店铺有哪些优惠券
    @ApiOperation("查询店铺有哪些优惠券")
    @GetMapping("/getDiscBySid")
    @JsonIgnoreProperties(value = "headller")
    public RespBean getDiscBySid(@ApiParam("店铺id") Integer id){
        List<ViewDiscount> discountList = discountService.getDiscBySid(id);
        return RespBean.respSuccess("查询成功",discountList);
    }

    //根据session里的店铺id获取优惠券
    @ApiOperation("根据session里的店铺id获取优惠券")
    @GetMapping("/getDiscBySessionId")
    @JsonIgnoreProperties(value = "headller")
    public RespBean getDiscBySessionId(HttpServletRequest request){
        Integer storeId = (Integer) request.getSession().getAttribute("storeId");
        List<ViewDiscount> discountList = discountService.getDiscBySid(storeId);
        return RespBean.respSuccess("查询成功",discountList);
    }

    //根据商品ID查询优惠券
    @GetMapping("/getDiscByPid")
    public RespBean getDiscByPid(Integer pid){
        List<ViewDiscount> discountList =  discountService.queryDiscountByPId(pid);
        return RespBean.respSuccess("查询成功",discountList);
    }

    //查询用户当前订单能用哪些优惠券


    //查询用户未使用的优惠券
    @GetMapping("/getNotUse")
    public RespBean getNotUse(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<ViewDiscount> discountList = discountService.queryDiscountByUid(user.getId());
        List<ViewDiscount> viewDiscounts = new ArrayList<>();
        for (ViewDiscount viewDiscount:discountList){
            if (viewDiscount.getIsUse() == 1){
                viewDiscounts.add(viewDiscount);
            }
        }
        return RespBean.respSuccess("查询成功",viewDiscounts);
    }

    //查询用户已经使用的优惠券
    @GetMapping("/getUse")
    public RespBean getUse(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<ViewDiscount> discountList = discountService.queryDiscountByUid(user.getId());
        List<ViewDiscount> viewDiscounts = new ArrayList<>();
        for (ViewDiscount viewDiscount:discountList){
            if (viewDiscount.getIsUse() == 0){
                viewDiscounts.add(viewDiscount);
            }
        }
        return RespBean.respSuccess("查询成功",viewDiscounts);
    }

    //查询用户已经过期的优惠券
    @GetMapping("/getOverdue")
    public RespBean getOverdue(HttpSession session) throws ParseException {
        User user = (User) session.getAttribute("user");
        List<ViewDiscount> discountList = discountService.queryDiscountByUid(user.getId());
        List<ViewDiscount> viewDiscounts = new ArrayList<>();
        long time = new Date().getTime();
        for (ViewDiscount viewDiscount:discountList){
            String releaseTime = viewDiscount.getReleaseTime();
            Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(releaseTime);
            long validity = viewDiscount.getValidity()*1000*60*60*24;
            if (time > parse.getTime()+validity){
                //未过期
                viewDiscounts.add(viewDiscount);
            }
        }
        return RespBean.respSuccess("查询成功",viewDiscounts);
    }


    //根据订单id查询满足订单的优惠券
    @GetMapping("/getAvailableDis")
    public RespBean getAvailableDis(HttpSession session,Integer id) throws ParseException {
        //获取当前登录的用户信息
        User user = (User) session.getAttribute("user");

        //根据订单id获取当前订单对应的商品
        List<ViewOrderDetails> viewOrderDetails = orderService.queryOrderDetailsByOrderId(id);

        //根据用户ID查询用户有哪些未使用并且未过期的的优惠券
        List<ViewDiscount> discountList = discountService.queryDiscountByUid(user.getId());
        List<ViewDiscount> viewDiscounts = new ArrayList<>(); //viewDiscounts中保存的是用户拥有且未使用且未过期的优惠券
        long time = new Date().getTime();
        String releaseTime = null;
        long validity = 0L;
        Date parse = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ViewDiscount viewDiscount:discountList){
            releaseTime = viewDiscount.getReleaseTime();
            parse = sdf.parse(releaseTime);
            validity = viewDiscount.getValidity()*1000*60*60*24;
            if (viewDiscount.getIsUse() == 1 && time < (parse.getTime()+validity)){
                viewDiscounts.add(viewDiscount);
            }
        }

        if (viewDiscounts.size() == 0)
            return RespBean.respError("当前用户没有优惠券可以使用");
        //判断哪些优惠券符合使用条件 , 将符合条件的优惠券保存到 availableList 中
        ArrayList<ViewDiscount> availableList = new ArrayList<>();

        //根据商品去查询对应针对商品符合条件的优惠券
        for (int i=0;i<viewOrderDetails.size();i++){
            for (int j = 0; j < viewDiscounts.size(); j++) {
                if ((viewOrderDetails.get(i).getPid()==viewDiscounts.get(j).getPid())
                        && (viewOrderDetails.get(i).getPrice()*viewOrderDetails.get(i).getNumber() > viewDiscounts.get(j).getDoorSill()) ){
                    //满足使用条件，把优惠券加入到可用集合里面
                    availableList.add(viewDiscounts.get(j));
                }
            }
        }

        //根据店铺类型优惠券去查询符合条件的优惠券
        double totalPrice = 0.0;
        for (int i = 0; i < viewDiscounts.size(); i++) {
            for (int j = 0; j < viewOrderDetails.size(); j++) {
                if (viewDiscounts.get(i).getSid() == viewOrderDetails.get(j).getSid()){
                    totalPrice = totalPrice+ viewOrderDetails.get(j).getPrice()*viewOrderDetails.get(j).getNumber();
                }
            }
            if (totalPrice > viewDiscounts.get(i).getDoorSill()){
                availableList.add(viewDiscounts.get(i));
            }
            totalPrice = 0.0;
        }

        return RespBean.respSuccess("查询成功",availableList);
    }
}
